#include "login.h"
#include "ui_login.h"

#include "serialserver.h"
#include "databases.h"
#include <QDebug>
#include <QSqlError>
#include <QMessageBox>


Login::Login(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Login)
{
    ui->setupUi(this);
    this->setWindowTitle("Login");
    this->setFixedSize(640,480);



}

QString Login::access = "0";

Login::~Login()
{
    delete ui;
}

void Login::on_loginBtn_clicked()
{
    SerialServer* serialserver = new SerialServer;
    if(!this->login())
    {
        this->hide();
        serialserver->show();
    }
}

bool Login::login()
{
    QSqlQuery query;

    //获取输入的账号和密码
    QString username = ui->userline->text();
    QString password = ui->pwline->text();

    //查询表中的账号和密码
    query.prepare("select * from logininfo where account = :username AND passwd = :password");

    //绑定输入的账号(账号) 和 数据库中的 账号(密码)
    query.bindValue(":username",username);
    query.bindValue(":password",password);

    // 判断是否成功执行查询语句
    if(query.exec())
    {
        //判断是否存在下一条记录
        if(query.next())
        {
            //将当前登录的用户的权限 "2"为超级用户
            query.exec(QString("select access from logininfo where account = '%1'").arg(username));

            // 遍历结果集
            while (query.next())
            {
                access = query.value(0).toString();

            }
            return false;
        }
        else
        {
            // 不存在账号(密码) 匹配的情况
            QMessageBox falBox;
            falBox.setWindowTitle("登录失败");
            falBox.setText("登录失败，请重新登录");

            //设置登录失败弹出窗口
            falBox.setIcon(QMessageBox::Information);
            falBox.exec();
        }
    }

}




void Login::on_exitBtn_clicked()
{
    this->close();
}

